/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.zhike.framework.common.util;

import com.huize.ladon.apm.common.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 描述: BI数据收集 解码器
 *
 * @author tianyuliang
 * @version $Id: CollectDataUtils.java, v0.1 2020/5/27
 */
@Slf4j
public class CollectDataUtils {

    private static final String SPLIT_SINGLE_CHAR = "&";

    private static final String SPLIT_CHAR = "[&]";

    /**
     * 先URL解码,后base64解码
     */
    public static String decryptDefaultCollectData(String value) {
        if (BaseUtils.isEmpty(value)) {
            return StringUtils.EMPTY;
        }
        if (value.trim().contains(SPLIT_SINGLE_CHAR)) {
            return decryptCollectData(value.trim());
        }

        try {
            byte[] bytes = Base64.decodeBase64(value.trim());
            String source = new String(bytes);
            return source;
        } catch (Exception e) {
            log.error("resolve base64 error. value = {}", value, e);
        }
        return "";
    }

    /**
     * 先URL解码,后base64解码
     */
    private static String decryptCollectData(String value) {
        if (BaseUtils.isEmpty(value)) {
            return StringUtils.EMPTY;
        }
        try {
            String origin = URLDecoder.decode(value.trim(), CommonConstants.UTF8);
            String[] values = origin.trim().split(SPLIT_CHAR);
            // Stream.of(values).forEach(item -> System.out.println(item));
            String base64 = values[0];
            String source = new String(Base64.decodeBase64(base64));
            return source;
        } catch (UnsupportedEncodingException e) {
            log.error("resolve base64 error. value = {}", value, e);
        }
        return "";
    }

    public static void main(String[] args) {
        String input = "eyJkaXN0aW5jdF9pZCI6IjE3NDY3OWUzY2UxYjUtMGM2N2M1M2RjNjBiZTktNWUxYTNmMTgtMjA3MzYwMC0xNzQ2NzllM2NlMjc5OSIsImxpYiI6eyIkbGliIjoianMiLCIkbGliX21ldGhvZCI6ImNvZGUiLCIkbGliX3ZlcnNpb24iOiIwLjcuMCJ9LCJhcHAiOnsiJGFwcF9pZCI6IjI3OTNjM2ZkMWR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